package leetcodeHis.算法总纲.链表;


public class 链表反转 {

    /**
     * 递归反转链表
     * @param node
     * @return
     */
    public static ListNode reverse(ListNode node) {
        if(node.next == null) {
            return node;
        }
        ListNode newHead = reverse(node.next);
        node.next.next = node;                  //这里会形成环
        node.next = null;

        return newHead;
    }

    public static ListNode normalReverse(ListNode node) {
        ListNode pre = node;
        ListNode cur = pre.next;
        pre.next = null;
        while (cur != null) {
            ListNode next = cur.next;
            cur.next = pre;
            pre = cur;
            cur = next;
        }
        return pre;
    }

    public static void main(String[] args) {
        ListNode node = new ListNode(-1);
        node.next = new ListNode(0);
        node.next.next = new ListNode(1);
        node.next.next.next = new ListNode(2);
        node.next.next.next.next = new ListNode(3);

        ListNode result = normalReverse(node.next);
        ListNode head = result;
        while (head!=null) {
            System.out.print(head.val);
            head = head.next;
        }
    }
}
